<template>
  <div class="forgot-password-container">
    <div class="forgot-password-card">
      <!-- 头部 -->
      <div class="forgot-password-header">
        <h1 class="forgot-password-title">{{ $t('auth.forgotPassword.title') }}</h1>
        <p class="forgot-password-subtitle">{{ $t('auth.forgotPassword.subtitle') }}</p>
      </div>

      <!-- 表单 -->
      <el-form
        ref="forgotPasswordFormRef"
        :model="forgotPasswordForm"
        :rules="forgotPasswordRules"
        class="forgot-password-form"
        @submit.prevent="handleForgotPassword"
      >
        <!-- 邮箱输入 -->
        <el-form-item prop="email">
          <el-input
            v-model="forgotPasswordForm.email"
            type="email"
            :placeholder="$t('auth.forgotPassword.emailPlaceholder')"
            size="large"
            class="forgot-password-input"
            :disabled="loading"
          >
            <template #prefix>
              <el-icon><Message /></el-icon>
            </template>
          </el-input>
        </el-form-item>

        <!-- 图形验证码 -->
        <el-form-item prop="captcha">
          <div class="captcha-form-item">
            <el-input
              v-model="forgotPasswordForm.captcha"
              :placeholder="$t('auth.forgotPassword.captchaPlaceholder')"
              size="large"
              class="captcha-input"
              :disabled="loading"
              maxlength="4"
            >
              <template #prefix>
                <el-icon><Key /></el-icon>
              </template>
            </el-input>
            <Captcha
              ref="captchaRef"
              @change="handleCaptchaChange"
              class="captcha-component"
            />
          </div>
        </el-form-item>

        <!-- 新密码 -->
        <el-form-item prop="newPassword">
          <el-input
            v-model="forgotPasswordForm.newPassword"
            type="password"
            :placeholder="$t('auth.forgotPassword.newPasswordPlaceholder')"
            size="large"
            class="forgot-password-input"
            :disabled="loading"
            show-password
          >
            <template #prefix>
              <el-icon><Lock /></el-icon>
            </template>
          </el-input>
        </el-form-item>

        <!-- 确认密码 -->
        <el-form-item prop="confirmPassword">
          <el-input
            v-model="forgotPasswordForm.confirmPassword"
            type="password"
            :placeholder="$t('auth.forgotPassword.confirmPasswordPlaceholder')"
            size="large"
            class="forgot-password-input"
            :disabled="loading"
            show-password
          >
            <template #prefix>
              <el-icon><Lock /></el-icon>
            </template>
          </el-input>
        </el-form-item>

        <!-- 提交按钮 -->
        <el-form-item>
          <el-button
            type="primary"
            size="large"
            class="forgot-password-btn"
            :loading="loading"
            :disabled="loading"
            @click="handleForgotPassword"
          >
            <el-icon v-if="!loading"><Check /></el-icon>
            {{ loading ? $t('auth.forgotPassword.resetting') : $t('auth.forgotPassword.resetPassword') }}
          </el-button>
        </el-form-item>

        <!-- 返回登录 -->
        <el-form-item>
          <div class="back-to-login">
            <router-link to="/login" class="back-link">
              <el-icon><ArrowLeft /></el-icon>
              {{ $t('auth.forgotPassword.backToLogin') }}
            </router-link>
          </div>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import { Message, Key, Lock, Check, ArrowLeft } from '@element-plus/icons-vue'
import { useI18n } from 'vue-i18n'
import Captcha from '../../components/Captcha.vue'
import { authApi } from '../../services/api'

const router = useRouter()
const { t } = useI18n()

// 表单引用
const forgotPasswordFormRef = ref<FormInstance>()
const captchaRef = ref()

// 加载状态
const loading = ref(false)

// 表单数据
const forgotPasswordForm = reactive({
  email: '',
  captcha: '',
  newPassword: '',
  confirmPassword: ''
})

// 存储验证码
const sessionCaptcha = ref('')

// 表单验证规则
const forgotPasswordRules: FormRules = {
  email: [
    { required: true, message: t('auth.forgotPassword.emailRequired'), trigger: 'blur' },
    { type: 'email', message: t('auth.forgotPassword.emailFormat'), trigger: 'blur' }
  ],
  captcha: [
    { required: true, message: t('auth.forgotPassword.captchaRequired'), trigger: 'blur' },
    { min: 4, max: 4, message: t('auth.forgotPassword.captchaLength'), trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: t('auth.forgotPassword.newPasswordRequired'), trigger: 'blur' },
    { min: 6, max: 50, message: t('auth.forgotPassword.passwordLength'), trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: t('auth.forgotPassword.confirmPasswordRequired'), trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== forgotPasswordForm.newPassword) {
          callback(new Error(t('auth.forgotPassword.passwordMismatch')))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 处理验证码变化
const handleCaptchaChange = (code: string) => {
  sessionCaptcha.value = code
}

// 处理忘记密码提交
const handleForgotPassword = async () => {
  if (!forgotPasswordFormRef.value) return

  try {
    // 验证表单
    await forgotPasswordFormRef.value.validate()
    
    // 验证图形验证码
    if (!captchaRef.value?.validate(forgotPasswordForm.captcha)) {
      ElMessage.error(t('auth.forgotPassword.captchaError'))
      return
    }

    loading.value = true

    // 调用API重置密码
    const response = await authApi.forgotPassword({
      email: forgotPasswordForm.email,
      captcha: forgotPasswordForm.captcha,
      new_password: forgotPasswordForm.newPassword
    })

    if (response.code === 200) {
      ElMessage.success(response.message || t('auth.forgotPassword.resetSuccess'))
      // 重置成功后跳转到登录页面
      setTimeout(() => {
        router.push('/login')
      }, 1500)
    } else {
      ElMessage.error(response.message || t('auth.forgotPassword.resetFailed'))
    }
  } catch (error: any) {
    console.error('忘记密码错误:', error)
    ElMessage.error(error.message || t('auth.forgotPassword.resetFailed'))
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
.forgot-password-container {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20px;
}

.forgot-password-card {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-radius: 20px;
  padding: 40px;
  width: 100%;
  max-width: 450px;
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
}

.forgot-password-header {
  text-align: center;
  margin-bottom: 30px;
}

.forgot-password-title {
  font-size: 28px;
  font-weight: 700;
  color: #2c3e50;
  margin: 0 0 10px 0;
  background: linear-gradient(135deg, #667eea, #764ba2);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.forgot-password-subtitle {
  color: #7f8c8d;
  font-size: 14px;
  margin: 0;
  line-height: 1.5;
}

.forgot-password-form {
  width: 100%;
}

.forgot-password-input {
  width: 100%;
}

.captcha-form-item {
  display: flex;
  gap: 12px;
  align-items: flex-start;
}

.captcha-input {
  flex: 1;
}

.captcha-component {
  flex-shrink: 0;
}

.forgot-password-btn {
  width: 100%;
  height: 48px;
  font-size: 16px;
  font-weight: 600;
  background: linear-gradient(135deg, #667eea, #764ba2);
  border: none;
  border-radius: 12px;
  transition: all 0.3s ease;
}

.forgot-password-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(102, 126, 234, 0.4);
}

.forgot-password-btn:disabled {
  transform: none;
  box-shadow: none;
}

.back-to-login {
  text-align: center;
  margin-top: 20px;
}

.back-link {
  display: inline-flex;
  align-items: center;
  gap: 6px;
  color: #7f8c8d;
  text-decoration: none;
  font-size: 14px;
  transition: color 0.3s ease;
}

.back-link:hover {
  color: #667eea;
}

/* 深色主题适配 */
@media (prefers-color-scheme: dark) {
  .forgot-password-card {
    background: rgba(44, 62, 80, 0.95);
    border: 1px solid rgba(255, 255, 255, 0.1);
  }

  .forgot-password-title {
    color: #ecf0f1;
  }

  .forgot-password-subtitle {
    color: #bdc3c7;
  }

  .back-link {
    color: #bdc3c7;
  }

  .back-link:hover {
    color: #667eea;
  }
}

/* 响应式设计 */
@media (max-width: 480px) {
  .forgot-password-container {
    padding: 10px;
  }

  .forgot-password-card {
    padding: 30px 20px;
  }

  .forgot-password-title {
    font-size: 24px;
  }

  .captcha-form-item {
    flex-direction: column;
    gap: 8px;
  }

  .captcha-input {
    width: 100%;
  }
}
</style>
